/**
 * Copyright 2012 ibiblio
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0.txt
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.ibiblio.terasaur.db;

import java.util.Properties;

import org.hibernate.dialect.Dialect;
import org.hibernate.dialect.PostgreSQLDialect;
import org.hibernate.id.PersistentIdentifierGenerator;
import org.hibernate.id.SequenceGenerator;
import org.hibernate.type.Type;

/**
 * See <a href='http://www.hibernate.org/296.html'>http://www.hibernate.org/296.html</a>
 */
public class TerasaurPostgreSQLDialect extends PostgreSQLDialect {

    /**
     * Get the native identifier generator class.
     *
     * @return TableNameSequenceGenerator.
     */
    @Override
    public Class<?> getNativeIdentifierGeneratorClass() {
        return TerasaurPostgreSQLSequenceGenerator.class;
    }

    /**
     * Creates a sequence per table instead of the default behavior of one
     * sequence.
     */
    public static class TerasaurPostgreSQLSequenceGenerator extends SequenceGenerator {
        /**
         * {@inheritDoc} If the parameters do not contain a {@link SequenceGenerator#SEQUENCE}
         * name, we assign one based on the table name.
         */
        @Override
        public void configure(final Type type, final Properties params, final Dialect dialect) {
            if (params.getProperty(SEQUENCE) == null
                    || params.getProperty(SEQUENCE).length() == 0) {
                String tableName = params.getProperty(PersistentIdentifierGenerator.TABLE);
                if (tableName != null) {
                    params.setProperty(SEQUENCE, tableName + "_seq");
                }
            }
            super.configure(type, params, dialect);
        }
    }

    public String getIdentitySelectString(String table, String column, int type) {
        String seq_s = new StringBuilder().append("select currval('")
                .append(table)
                .append("_seq')")
                .toString();
        return seq_s;
    }
}